import argparse
from . import config
import logging
import sys
sys.path.append(config.pj_root)
import steward as st
from . import build


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--to_load')
    parser.add_argument('-s', '--to_save')
    parser.add_argument('--list', default='0')
    args = parser.parse_args()
    if args.to_save is not None:
        args.to_save = args.to_save.split(',')
        args.to_save = [s.strip() for s in args.to_save]
    else:
        args.to_save = []

    if args.to_load is not None:
        args.to_load = args.to_load.split(',')
        args.to_load = [s.strip() for s in args.to_load]
    else:
        args.to_load = []
    return args


def main():
    args = parse_args()
    build.build_all()

    if args.list != '0':
        print('regex:', args.list)
        print('select: ')
        for key in st.regex_select_instance(args.list):
            print(key)

    to_load = set()
    for load_regex in args.to_load:
        for load_name in st.regex_select_instance(load_regex):
            to_load.add(load_name)

    for load_name in to_load:
        logging.info('loading: %s' % load_name)
        st.load_from_file(st.get_instance(load_name))

    to_save = set()
    for save_regex in args.to_save:
        for save_name in st.regex_select_instance(save_regex):
            to_save.add(save_name)

    for save_name in to_save:
        logging.info('building: %s' % save_name)
        st.save_to_file(st.get_instance(save_name))

if __name__ == '__main__':
    main()

